const userService = require("../services/userService");
const { generateRandomCode } = require('../utils/utils')

const jwt = require('jsonwebtoken');
const { SECRET_KEY, Expiration } = require('../config/authConfig');

// 获取所有用户
async function getUsers(ctx, next) {
  try {
    const users = await userService.getUsers();
    ctx.body = { success: true, data: users };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "获取用户列表失败",
      error: error.message,
    };
  }
}

// 获取单个用户
async function getUser(ctx, next) {
  try {
    const { id } = ctx.params;
    const user = await userService.getUser(id);
    if (user) {
      ctx.body = { success: true, data: user };
    } else {
      ctx.status = 404;
      ctx.body = { success: false, message: "用户不存在" };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "获取用户失败",
      error: error.message,
    };
  }
}

// 创建用户
async function createUser(ctx, next) {
  try {
    const { name, password } = ctx.request.body;
    const newUser = await userService.createUser({ name, password });
    if (newUser) {
      ctx.body = { success: true, data: newUser };
    } else {
      ctx.status = 400;
      ctx.body = { success: false, message: "用户名已存在" };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "创建用户失败",
      error: error.message,
    };
  }
}

// 更新用户
async function updateUser(ctx, next) {
  try {
    const { id } = ctx.params;
    const { name, email, password } = ctx.request.body;
    const updated = await userService.updateUser({ id, name, email, password });
    if (updated) {
      ctx.body = { success: true, message: "用户更新成功" };
    } else {
      ctx.status = 404;
      ctx.body = { success: false, message: "用户不存在" };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "更新用户失败",
      error: error.message,
    };
  }
}

// 删除用户
async function deleteUser(ctx, next) {
  try {
    const { id } = ctx.params;
    const deleted = await userService.deleteUser(id);
    if (deleted) {
      ctx.body = { success: true, message: "用户删除成功" };
    } else {
      ctx.status = 404;
      ctx.body = { success: false, message: "用户不存在" };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "删除用户失败",
      error: error.message,
    };
  }
}

// 批量删除用户
async function deleteUsers(ctx, next) {
  try {
    const { userIds } = ctx.request.body;
    const deleted = await userService.deleteUsers(userIds);
    if (deleted) {
      ctx.body = { success: true, message: "用户批量删除成功" };
    } else {
      ctx.status = 400;
      ctx.body = { success: false, message: "用户批量删除失败" };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "批量删除用户失败",
      error: error.message,
    };
  }
}

// 用户登录
async function loginUser(ctx, next) {
  try {
    const { name, password } = ctx.request.body;
    const token = await userService.loginUser({ name, password });
    if (token) {
      ctx.body = { success: true, token };
    } else {
      ctx.status = 401;
      ctx.body = { success: false, message: "用户名或密码错误" };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { success: false, message: "登录失败", error: error.message };
  }
}

// 获取openid
async function getOpenid(ctx) {
  try {
    // 假设您已经通过微信登录获取了用户的 code
    const code = ctx.request.body.code;

    const res = await userService.getUserOpenID(code);

    // 在这里可以进行用户相关的操作，例如保存 OpenID 到数据库等
    const { openid } = res
    if(!openid) return ctx.body = res

    // 查询用户信息
    const user = await userService.getUserByOpenid(openid)

    if(!user) { // 没有注册
      const userData = {
        name: '微信用户 ' + generateRandomCode(),
        password: '123456',
        openid
      }
      const newUser = await userService.createUser(userData)
      const token = jwt.sign({ id: newUser.id, name: newUser.name, role: newUser.role }, SECRET_KEY, { expiresIn: Expiration });
      newUser.openid = openid
      return ctx.body = {...newUser, token}
    }
    const token = jwt.sign({ id: user.id, name: user.name, role: user.role }, SECRET_KEY, { expiresIn: Expiration });
    user.openid = openid
    return ctx.body = {...user, token}
  } catch (error) {
    // console.log(error, 'error');
    ctx.throw(500, "服务器内部错误");
  }
}

module.exports = {
  getUsers,
  getUser,
  createUser,
  updateUser,
  deleteUser,
  deleteUsers,
  loginUser,
  getOpenid,
};
